package mua.core.operation.other;

import mua.core.interpreter.Global;
import mua.core.value.MuaValue;
import mua.core.value.Number;
import mua.core.value.Word;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

public class Save {
    public static MuaValue run(MuaValue a) {
        try {
            File writeName = new File("./"+a.toString());
            if(!writeName.exists()){
                writeName.createNewFile();
            }
            FileWriter writer = new FileWriter(writeName);
            BufferedWriter out = new BufferedWriter(writer);
            StringBuilder data;
            for(Map.Entry<String, MuaValue> entry:Global.globalVariable.entrySet()){
                data = new StringBuilder();
                if(entry.getValue() instanceof Number){
                    data.append("make \"").append(entry.getKey()).append(" ").append((Double) entry.getValue().getValue()).append("\n");
                }else{
                    data.append("make \"").append(entry.getKey()).append(" ").append(entry.getValue().getValue()).append("\n");
                }
                out.write(data.toString());
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Word(a.toString());
    }
}
